<template>
	<div class="puzzle" ref="puzzleRef">
		<div class="puzzle-content" :style="{'width':data.contentWidth+'px','height':data.contentHeight+'px'}">
			<canvas id="puzzle" ref="puzzleDom"></canvas>
			<div class="puzzle-content-image" ref='puzzleContentImage' @click="phoneClick($event)" @dragstart="dragstart($event)" @drop="drop($event)" @dragover="dragover($event)">
				<div  class="puzzle-content-image-parent" :draggable="data.isDraggable"  v-for="(item,index) in data.totalCount" :style="{'width':data.imageWidth+'px','height':data.imageHeight+'px'}" >
					<canvas>{{data.derangedArray[index]}}</canvas>
					<strong v-if="data.isUseTp">{{data.isUseTp?data.TipArray[index] + 1:data.correctArray[index] + 1}}</strong>
				</div>
			</div>
			<div class="puzzle-content-defalue">
				<span><img draggable="false" :src="data.fileUrl"></span>
				<span v-for="(item,index) in 8" @click="selectImage($event)"><img draggable="false" :src="require('../../assets/image/puzzle/0'+(index+1)+'.jpg') "></span>
			</div>
			<div class="puzzle-content-bottom" @click="selectPatternClick($event)">
				<button :data-id='1' :class="{'activeButton':data.currentSelectId === 1}">简单</button>
				<button :data-id='2' :class="{'activeButton':data.currentSelectId === 2}">困难</button>
				<button :data-id='3' :class="{'activeButton':data.currentSelectId === 3}">超级</button>
			</div>
			<div class="puzzle-content-top">
				<button>{{data.gameTime}}</button>
				<a href="##" class="puzzle-content-top-file">选取图片<input @change="selectImageChange" type="file" name="" id="imageInput"></a>
				<button :class="{'activeButton':data.isStartGame}" @click="debounce(()=>{startGameClick()},500)()">{{data.isStartGame?'结束游戏':'开始游戏'}}</button>
				<button :class="{'activeButton':data.isUseTp}" @click="debounce(()=>{data.isUseTp = !data.isUseTp},500)()">{{data.isUseTp?'关闭提示':'开启提示'}}</button>
			</div>
		</div>
		
	</div>
</template>

<script lang="ts" setup>
	import { ref,onMounted,reactive,inject,onBeforeUnmount,watch } from 'vue'
	import { ElMessage,ElMessageBox} from 'element-plus'
	import {debounce,gameTimeMain} from '../../public/common'
	import { playAudio } from '../main/webServer'
	import {useTiming} from '../main/useChessboard.ts'
	import bus from '../../public/bus'
	let puzzleDom = ref<HTMLElement>();
	let puzzleContentImage = ref<HTMLElement>();
	let puzzleRef = ref<HTMLElement>();
	
	let data = reactive({
		currentSelectId:1,
		fileUrl:require('../../assets/image/puzzle/00.jpg'),
		totalCount:0,
		imageWidth:0,
		imageHeight:0,
		dragParent:null,
		derangedArray:[],//错乱数组
		correctArray:[],//正确数组
		isStartGame:0,
		isDraggable:false,
		contentWidth:440,
		contentHeight:600,
		isUseTp:false,
		TipArray:[],
		gameTime:'00:00:00',
		gameText:'',
		system:''
	})
	const startGameClick = ()=>{
		if(!data.fileUrl){
			ElMessage({
				message: '请先选取图片！',
				type: 'warning',
			})
			return
		}
		if(!data.currentSelectId){
			ElMessage({
				message: '请选择游戏模式！',
				type: 'warning',
			})
			return
		}
		if(data.isStartGame === 0){
			data.isStartGame = 1
			if(data.currentSelectId === 1){
				starDrawMain(data.fileUrl,9,3,3,true)
			}else if(data.currentSelectId === 2){
				starDrawMain(data.fileUrl,12,3,4,true)
			}else if(data.currentSelectId === 3){
				starDrawMain(data.fileUrl,16,4,4,true)
			}
			gameTimeMain.start((v)=>{
				data.gameTime = v.gameTime
				data.gameText = v.gameText
			})
		}else{
			data.isStartGame = 0
			if(data.currentSelectId === 1){
				starDrawMain(data.fileUrl,9,3,3)
			}else if(data.currentSelectId === 2){
				starDrawMain(data.fileUrl,12,3,4)
			}else if(data.currentSelectId === 3){
				starDrawMain(data.fileUrl,16,4,4)
			}
			gameTimeMain.stop((v)=>{
				data.gameTime = v.gameTime
				data.gameText = v.gameText
			})
		}
		
	}
	// 选择游戏模式
	const selectPatternClick = (event)=>{
		console.log(event)
		if(event.target.nodeName === 'BUTTON'){
			let id:number = Number(event.target.dataset.id)
			data.currentSelectId = id
		}
	}
	// 左侧选择图片
	const selectImage = (event)=>{
		if(data.isStartGame === 1){
			ElMessage({
				message: '游戏中禁止选择图片！',
				type: 'warning',
			})
			return
		}
		if(data.currentSelectId === 1){
			starDrawMain( event.target.src,9,3,3)
		}else if(data.currentSelectId === 2){
			starDrawMain( event.target.src,12,3,4)
		}else if(data.currentSelectId === 3){
			starDrawMain( event.target.src,16,4,4)
		}
	}
	// 选择图片
	const selectImageChange = (event)=>{
		if(data.isStartGame === 1){
			ElMessage({
				message: '游戏中禁止选择图片！',
				type: 'warning',
			})
			return
		}
		let file = event.target.files[0]
		console.log(file.type)
		if(file.type !== 'image/jpeg' && file.type !== 'image/gif' && file.type !== 'image/png'){
			ElMessage({
				message: '请选择.jpg,.gif,.png图片！',
				type: 'warning',
			})
			return
		}
		let fileUrl = URL.createObjectURL(file)
		if(data.currentSelectId === 1){
			starDrawMain(fileUrl,9,3,3)
		}else if(data.currentSelectId === 2){
			starDrawMain(fileUrl,12,3,4)
		}else if(data.currentSelectId === 3){
			starDrawMain(fileUrl,16,4,4)
		}
	}
	// 开始绘制 totalCount：总图片数量 countX：定义x方向图片个数，countY
	const starDrawMain = (fileUrl,totalCount,countX,countY,isDeranged)=>{
		let	imageArray = new Array(); //储存所有图片
		let image = new Image();
		image.src = fileUrl
		image.onload=function(){
			// 获取图片宽高,等比计算
			let contentWidth = 600/image.height*image.width
			let contentHeight = 600
			if(contentWidth > puzzleRef.value.clientWidth - 100){
				ElMessage({
					message: '您选择的图片尺寸过大，请重新选择！',
					type: 'warning',
				})
				return
			}
			data.fileUrl = fileUrl
			data.contentWidth = contentWidth
			data.contentHeight = contentHeight
			let puzzle = puzzleDom.value;
			let {contentWidth:clientWidth,contentHeight:clientHeight} = data
			console.log(clientWidth,clientHeight)
			puzzle.width = clientWidth
			puzzle.height = clientHeight
			let imageWidth = clientWidth / countX - 1, //计算每个图片宽度
				imageHeight = clientHeight / countY - 1, //计算每个图片高度
				x = 0,//计算x
				y = 0; //计算y
			
			let context = puzzle.getContext('2d');
			// 开始绘制
		     context.drawImage(image, 0, 0, clientWidth, clientHeight);
			 data.correctArray = []
			 imageArray = []
			 data.derangedArray = []
			 data.TipArray = []
			 for (var i = 0; i < totalCount; i++) {
			 	var contextData = context.getImageData(imageWidth * x, imageHeight * y, imageWidth, imageHeight);
			 	imageArray.push(contextData);
				data.correctArray.push(i)
			 	console.log(imageArray)
			 	if (x < countX - 1) {
			 		x++;
			 	} else {
			 		x = 0;
			 		y++;
			 	}
			 }
			 let contextNodes = null
			 let childNode = null
			 let correctArray = Object.assign([],data.correctArray)
			 correctArray.sort(()=>Math.random() - 0.5)
			 data.derangedArray = correctArray
			 data.TipArray = isDeranged?Object.assign([],data.derangedArray):data.correctArray
			 
			 console.log(data.derangedArray,data.TipArray)
			 data.totalCount = totalCount
			 data.imageWidth = imageWidth
			 data.imageHeight = imageHeight
			 data.isDraggable = isDeranged?true:false
			 setTimeout(()=>{
				 let childNodes = Array.prototype.slice.call(puzzleContentImage.value.childNodes)
				 
				 childNodes.splice(0,1)
				 childNodes.splice(childNodes.length - 1,1)
				 console.log(childNodes)
				 function t(count){
					 if(count < totalCount){
						 childNode = childNodes[count].childNodes[0]
						 childNode.width = imageWidth
						 childNode.height = imageHeight
						 childNode.id = isDeranged?data.derangedArray[count]:count
						 contextNodes = childNode.getContext('2d');
						 contextNodes.putImageData(isDeranged?imageArray[data.derangedArray[count]]:imageArray[count], 0, 0);
						 setTimeout(()=>{
							t(++count)
						 },100)
						 
					 }
				 }
				 t(0)
			 },200)
			 
		}
		
	}
	// 手机无法使用拖拽,点击代替
	const phoneClick = (event)=>{
		console.log(event)
		if(event.target.nodeName === 'CANVAS'  && data.isStartGame && !data.system){
			if(!data.dragParent){
				data.dragParent = event.target.parentNode
				event.target.style.border = '1px solid rgb(249, 171, 8)'
			}else{
				let dragId = Number(data.dragParent.childNodes[0].id)
				let dropId = Number(event.target.id)
				if(dragId === dropId){
					return
				}
				let dropParent = event.target.parentNode
				let dropChildNode = event.target
				let dragChildNode = data.dragParent.childNodes[0]
				dropParent.removeChild(event.target)
				data.dragParent.removeChild(dragChildNode)
				dropParent.insertBefore(dragChildNode,dropParent.firstChild)
				data.dragParent.insertBefore(dropChildNode,data.dragParent.firstChild)
				let a = null
				let b = null
				console.log(data.TipArray)
				data.TipArray.forEach((v,index)=>{
					if(v === dragId){
						a = index
					}
					if(v === dropId){
						b = index
					}
					if(index === data.TipArray.length - 1){
						console.log(a,b)
						if(a != null && b != null){
							console.log(data.TipArray[a],data.TipArray[b],dropId,dragId)
							data.TipArray[a] = dropId
							data.TipArray[b] = dragId
							console.log(data.TipArray)
							
						}
					}
				})
				playAudio(8)
				isSuccessMain()
				console.log(data.dragParent.childNodes[0])
				dropParent.childNodes[0].style.border = '0'
				data.dragParent = null
				
			}
		}
		
	}
	// 拖拽开始
	const dragstart = (event)=>{
		if(data.isStartGame && data.system){
			data.dragParent = event.target
		}
	}
	// 拖放
	const drop = (event)=>{
		event.preventDefault();
		if(data.dragParent && data.isStartGame && data.system){
			let dragId = Number(data.dragParent.childNodes[0].id)
			let dropId = Number(event.target.id)
			if(dragId === dropId){
				return
			}
			let dropParent = event.target.parentNode
			let dropChildNode = event.target
			let dragChildNode = data.dragParent.childNodes[0]
			dropParent.removeChild(event.target)
			data.dragParent.removeChild(dragChildNode)
			dropParent.insertBefore(dragChildNode,dropParent.firstChild)
			data.dragParent.insertBefore(dropChildNode,data.dragParent.firstChild)
			let a = null
			let b = null
			console.log(data.TipArray)
			data.TipArray.forEach((v,index)=>{
				if(v === dragId){
					a = index
				}
				if(v === dropId){
					b = index
				}
				if(index === data.TipArray.length - 1){
					console.log(a,b)
					if(a != null && b != null){
						console.log(data.TipArray[a],data.TipArray[b],dropId,dragId)
						data.TipArray[a] = dropId
						data.TipArray[b] = dragId
						console.log(data.TipArray)
						
					}
				}
			})
			playAudio(8)
			isSuccessMain()
			data.dragParent = null
		}
		
		
	}
	// 判断是否拼图成功
	const isSuccessMain = () =>{
		let count = 0
		data.TipArray.forEach((v,i)=>{
			if(i === v){
				count++
			}
			if(count === data.TipArray.length){
				bus.emit('tip',"恭喜您拼图完成,用时"+data.gameText+'！')
				playAudio(4)
				gameTimeMain.stop((v)=>{
					data.gameTime = v.gameTime
					data.gameText = v.gameText
				})
				data.isStartGame = 0
				data.isDraggable = false
			}
		})
	}
	// 拖拽结束
	const dragover = (event)=>{
		event.preventDefault();
	}
	
	onMounted(()=>{
		starDrawMain(data.fileUrl,9,3,3)
		setTimeout(()=>{
			playAudio(2)
		},1000)
		
		data.system = /(Win32|Win16|WinCE|Mac68K|MacIntel|MacIntel|MacPPC|Linux mips64)/i.test(navigator.platform);
	})
	onBeforeUnmount(()=>{
		playAudio(3)
		gameTimeMain.stop((v)=>{
			data.gameTime = v.gameTime
			data.gameText = v.gameText
		})
	})
</script>

<style lang="scss">
	.puzzle{
		width: 100%;
		height: calc(100%);
		background-color: white;
		position: relative;
		display: flex;
		justify-content: center;
		align-items: center;
		.puzzle-content{
			width: 440px;
			height: 600px;
			box-shadow: 0 0 10px 0 #aaa;
			position: relative;
			border-radius: 3px;
			.puzzle-content-image{
				position: absolute;
				left: 0;
				top: 0;
				width: 100%;
				height: 100%;
				z-index: 1;
				display: flex;
				justify-content: space-between;
				flex-wrap: wrap;
				overflow: hidden;
				.puzzle-content-image-parent{
					position: relative;
				}
				canvas{
					animation:example 1s 1 forwards
				}
				@keyframes example{
					from{
						opacity: 0;
					}
					to{
						opacity: 1;
					}
				}
				strong{
					position: absolute;
					left: 0;
					top: 0;
					font-size: 16px;
					color: black;
					z-index: 1;
					pointer-events: none;
					background-color: green;
					color: white;
					padding: 3px;
				}
			}
			.puzzle-content-defalue{
				position: absolute;
				left: -50px;
				top: 0px;
				span{
					display: block;
					width: 50px;
					height: 50px;
					background-color: white;
					border-radius: 5px;
					border-top-right-radius:0 ;
					border-bottom-right-radius: 0;
					border: 2px solid #dcb57a;
					margin-bottom: 10px;
					cursor: pointer;
					overflow: hidden;
					&:nth-of-type(1){
						border:2px solid #e46606;
						margin-bottom: 30px;
					}
					&:hover{
						opacity: 0.8;
					}
					img{
						width: 100%;
						height: 100%;
						object-fit: cover;
						user-drag:none;
					}
				}
			}
			#puzzle{
				width: 100%;
				height: 100%;
				opacity: 0;
			}
			.puzzle-content-top{
				position: absolute;
				right: -81px;
				top: 0px;
				button{
					display: block;
					width: 80px;
					height: 30px;
					background-color: white;
					border-radius: 5px;
					border-top-left-radius:0 ;
					border-bottom-left-radius: 0;
					border: 1px solid #dcb57a;
					border-left: 0;
					margin-bottom: 10px;
					cursor: pointer;
					&:nth-of-type(1){
						margin-bottom: 30px;
					}
					&:hover{
						opacity: 0.8;
					}
				}
				
				.puzzle-content-top-file {
				   display: block;
				   width: 80px;
				   height: 30px;
				   line-height: 30px;
				   text-align: center;
				   font-size: 14px;
				   text-decoration: none;
				   background-color: white;
				   border-radius: 5px;
				   border-top-left-radius:0 ;
				   border-bottom-left-radius: 0;
				   border: 1px solid #dcb57a;
				   border-left: 0;
				   margin-bottom: 10px;
				   cursor: pointer;
				   color: black;
				   cursor: pointer;
				   position: relative;
				   overflow: hidden;
				   &:hover{
				   	opacity: 0.8;
				   }
					input {
					    position: absolute;
					    font-size: 100px;
						width: 100%;
						height: 100%;
					    right: 0;
					    top: 0;
					    opacity: 0;
						outline: none;
					}
					
				}
				
			}
			.puzzle-content-bottom{
				position: absolute;
				right: -80px;
				bottom: 10px;
				button{
					display: block;
					width: 80px;
					height: 30px;
					background-color: white;
					border-radius: 5px;
					border-top-left-radius:0 ;
					border-bottom-left-radius: 0;
					border: 1px solid #dcb57a;
					border-left: 0;
					margin-bottom: 10px;
					cursor: pointer;
					
					&:hover{
						opacity: 0.8;
					}
				}
				
			}
		}
		.activeButton{
			background-color: #dcb57a!important;
			color: white;
		}
		
	}
</style>
